"""
组织领域实体
定义组织领域中的核心实体对象
"""

from dataclasses import dataclass
from typing import Dict, List, Optional, Union
from datetime import datetime


@dataclass
class OrganizationOverview:
    """组织概览信息"""
    total_employees: int
    formal_employees: int
    gender_ratio: str
    average_age: float
    average_tenure: float
    management_positions: int
    average_reporting_depth: float
    average_management_span: float
    probation_employees: int
    party_member_ratio: float
    campus_recruit_ratio: float
    new_employee_ratio: float
    annual_turnover_rate: float
    management_ratio: float

    @classmethod
    def from_dict(cls, data: dict) -> 'OrganizationOverview':
        # 处理平均司龄，将"年月"格式转换为年数
        tenure_str = data.get("平均司龄", "0年0月")
        years = 0.0
        if "年" in tenure_str:
            years_str = tenure_str.split("年")[0]
            years = float(years_str)
            if "月" in tenure_str:
                months_str = tenure_str.split("年")[1].split("月")[0]
                years += float(months_str) / 12

        return cls(
            total_employees=int(data.get("总人数", 0)),
            formal_employees=int(data.get("正式工总人数", 0)),
            gender_ratio=data.get("男女比例", ""),
            average_age=float(data.get("平均年龄", "0").replace("岁", "")),
            average_tenure=years,
            management_positions=int(data.get("管理岗人数", 0)),
            average_reporting_depth=float(data.get("平均汇报深度", 0)),
            average_management_span=float(data.get("平均管理幅度", 0)),
            probation_employees=int(data.get("试用期人数", 0)),
            party_member_ratio=float(data.get("党员比例", "0").replace("%", "")) / 100,
            campus_recruit_ratio=float(data.get("校招生比例", "0").replace("%", "")) / 100,
            new_employee_ratio=float(data.get("近一年新员工比例", "0").replace("%", "")) / 100,
            annual_turnover_rate=float(data.get("近一年离职率", "0").replace("%", "")) / 100,
            management_ratio=float(data.get("官兵比", "0").split(":")[1]) if ":" in data.get("官兵比", "0") else 0
        )


@dataclass
class EfficiencyAnalysis:
    """人效分析数据"""
    profit_per_capita: float
    gross_profit_per_capita: float
    income_per_capita: float

    @classmethod
    def from_dict(cls, data: dict) -> 'EfficiencyAnalysis':
        return cls(
            profit_per_capita=float(data.get("人均利润", 0)),
            gross_profit_per_capita=float(data.get("人均毛利", 0)),
            income_per_capita=float(data.get("人均收入", 0))
        )


@dataclass
class TeamPerformance:
    """团队业绩数据"""
    daily_balance: float
    net_operating_income: float
    efficiency: float
    deposit_increment: float
    loan_increment: float
    loan_scale: float

    @classmethod
    def from_dict(cls, data: dict) -> 'TeamPerformance':
        return cls(
            daily_balance=float(data.get("日均余额", 0)),
            net_operating_income=float(data.get("营业净收入", 0)),
            efficiency=float(data.get("人效", 0)),
            deposit_increment=float(data.get("存款增量", 0)),
            loan_increment=float(data.get("贷款增量", 0)),
            loan_scale=float(data.get("贷款规模", 0))
        )


@dataclass
class CustomerAnalysis:
    """客群分析数据"""
    total_customers: int
    high_value_customers: int
    medium_large_customers: int
    basic_customers: int
    long_tail_customers: int

    @classmethod
    def from_dict(cls, data: dict) -> 'CustomerAnalysis':
        return cls(
            total_customers=int(data.get("总客群数", 0)),
            high_value_customers=int(data.get("高价值客群数", 0)),
            medium_large_customers=int(data.get("大中客群数", 0)),
            basic_customers=int(data.get("基础客群数", 0)),
            long_tail_customers=int(data.get("长尾客群数", 0))
        )


@dataclass
class Distribution:
    """通用分布数据"""
    current: Dict[str, float]  # 当前数据
    previous: Dict[str, float]  # 上一期数据
    change: Dict[str, float]   # 变化数据
    categories: List[str]      # 类别列表

    @classmethod
    def from_dict(cls, data: dict) -> 'Distribution':
        """从字典创建分布实例"""
        current_data = {}
        previous_data = {}
        change_data = {}
        categories = []
        
        if isinstance(data, dict):
            for key, value in data.items():
                categories.append(key)
                if isinstance(value, dict):
                    current_data[key] = value.get('current', 0)
                    previous_data[key] = value.get('previous', 0)
                    change_data[key] = value.get('change', 0)
                else:
                    current_data[key] = value
                    previous_data[key] = 0
                    change_data[key] = 0
        
        return cls(
            current=current_data,
            previous=previous_data,
            change=change_data,
            categories=categories
        )


@dataclass
class ComparisonResult:
    """对比结果实体类"""
    api_data: Union[int, Dict[str, float]]  # API数据 (总数或分布数据)
    db_data: Union[int, Dict[str, float]]   # 数据库数据 (总数或分布数据)
    match_rate: float                        # 匹配率 (0-100)
    is_matched: bool                         # 是否匹配
    error: Optional[str] = None             # 错误信息

    @classmethod
    def from_dict(cls, data: Dict) -> 'ComparisonResult':
        """从字典创建对比结果实例"""
        return cls(
            api_data=data.get('api_data'),
            db_data=data.get('db_data'),
            match_rate=float(data.get('match_rate', 0)),
            is_matched=bool(data.get('is_matched', False)),
            error=data.get('error')
        )

    def to_dict(self) -> Dict:
        """转换为字典"""
        return {
            'api_data': self.api_data,
            'db_data': self.db_data,
            'match_rate': self.match_rate,
            'is_matched': self.is_matched,
            'error': self.error
        } 